package com.my.roco.controller;

import com.my.roco.pojo.Love;
import com.my.roco.pojo.Pet;
import com.my.roco.pojo.Skill;
import com.my.roco.pojo.User; 
import com.my.roco.service.LoveService;
import com.my.roco.service.PetService;
import com.my.roco.service.SkillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.IOException;
import java.util.List;


@Controller
public class PetController {

    @Autowired
    private PetService petService;
    @Autowired
    private SkillService skillService;
    
    @Autowired
    private LoveService loveService; 
    
    @GetMapping("/home")
    public ModelAndView showHomePage() {
        ModelAndView mv = new ModelAndView();
        List<Pet> pets = petService.getAllPets();
        mv.addObject("pets", pets);
        mv.setViewName("home");
        return mv;
    }

    @GetMapping("/petList")
    public String petList(
        @RequestParam(required = false) String keyword,
        @RequestParam(required = false) String attribute,
        @RequestParam(required = false) String sortField,
        @RequestParam(required = false, defaultValue = "asc") String sortOrder,
        Model model
    ) {
        List<Pet> pets = petService.getPetsByCondition(keyword, attribute, sortField, sortOrder);
        model.addAttribute("pets", pets);
        model.addAttribute("keyword", keyword);
        model.addAttribute("attribute", attribute);
        model.addAttribute("sortField", sortField);
        model.addAttribute("sortOrder", sortOrder);
        return "petList";
    }
    
    @GetMapping("/myInfo")
    public String showMyInfoPage(HttpSession session) {
        return "myInfo"; 
    }
    
    @GetMapping("/petDetail")
    public ModelAndView showPetDetail(@RequestParam("number") String number, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        Pet pet = petService.getPetByNumber(number);
        List<Skill> skills = skillService.getSkillsByPetNumber(number); 
        
        boolean isLoved = false;
        if (session.getAttribute("user") != null) {
            String userAccount = ((User) session.getAttribute("user")).getAccount();
            isLoved = loveService.isLoved(userAccount, number);
        }
        
        mv.addObject("pet", pet);
        mv.addObject("skills", skills);
        mv.addObject("isLoved", isLoved); 
        
        mv.setViewName("petDetail");
        return mv;
    }

    @GetMapping("/addPetPage")
    public String showAddPetPage() {
        return "addPet";
    }

    @PostMapping("/addPet")
    public String addPet(@RequestParam("name") String name,
                         @RequestParam("number") String number,
                         @RequestParam("image") MultipartFile image,
                         @RequestParam("attribute") String attribute,
                         @RequestParam("energy") int energy,
                         @RequestParam("attack") int attack,
                         @RequestParam("magicAttack") int magicAttack,
                         @RequestParam("speed") int speed,
                         @RequestParam("magicDefense") int magicDefense,
                         @RequestParam("defense") int defense,
                         @RequestParam("height") double height,
                         @RequestParam("weight") double weight,
                         @RequestParam("introduction") String introduction,
                         @RequestParam("preEvolutionNumber") String preEvolutionNumber,
                         @RequestParam(value = "postEvolutionNumber", required = false) String postEvolutionNumber,
                         Model model,
                         HttpServletRequest request) {

        if (petService.existsByName(name)) {
            model.addAttribute("error", "宠物名称已存在");
            return "addPet";
        }

        if (petService.existsByNumber(number)) {
            model.addAttribute("error", "宠物编号已存在");
            return "addPet";
        }

        Pet pet = new Pet();
        pet.setName(name);
        pet.setNumber(number);
        pet.setAttribute(attribute);
        pet.setEnergy(energy);
        pet.setAttack(attack);
        pet.setMagicAttack(magicAttack);
        pet.setSpeed(speed);
        pet.setMagicDefense(magicDefense);
        pet.setDefense(defense);
        pet.setHeight(height);
        pet.setWeight(weight);
        pet.setIntroduction(introduction);
        pet.setPreEvolutionNumber(preEvolutionNumber);
        pet.setPostEvolutionNumber(postEvolutionNumber);

        String imagePath = "/resources/images/default/roco.png";
        if (!image.isEmpty()) {
            try {
                ServletContext context = request.getServletContext();
                String uploadDir = context.getRealPath("/resources/images/pets/");
                
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                
                String fileName = number + "_" + image.getOriginalFilename();
                File dest = new File(uploadDir + File.separator + fileName);
                image.transferTo(dest);
                
                imagePath = "/resources/images/pets/" + fileName;
            } catch (IOException e) {
                e.printStackTrace();
                model.addAttribute("error", "文件上传失败");
                return "addPet";
            }
        }
        pet.setImage(imagePath);

        petService.addPet(pet);
        return "redirect:/petList";
    }
    @PostMapping("/toggleLove")
    public String toggleLove(@RequestParam("petNumber") String petNumber, HttpSession session) {
        String userAccount = ((User) session.getAttribute("user")).getAccount();
        if (loveService.isLoved(userAccount, petNumber)) {
            loveService.removeLove(userAccount, petNumber);
        } else {
            Love love = new Love();
            love.setUserAccount(userAccount);
            love.setPetNumber(petNumber);
            loveService.addLove(love);
        }
        return "redirect:/petDetail?number=" + petNumber;
    }
    
    @GetMapping("/deletePet")
    public String deletePet(@RequestParam("number") String number) {
        petService.deletePet(number);
        return "redirect:/petList";
    }
}